package com.zxl.security.core.social.weixin.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class WeiXinImpl extends AbstractOAuth2ApiBinding implements WeiXin {
    /** 这里不需要去处理access_token，内置在发restTemplate请求的时候，拦截器帮我们在后面拼接access_token参数过去 */
    private static final String URL_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?openid=";

    public WeiXinImpl(String accessToken) {
        // 指定参数是通过?k=v方式进行发送
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }

    @Override
    public WeiXinUserInfo getUserInfo(String openId) {
        String url = URL_GET_USER_INFO + openId;
        String response = getRestTemplate().getForObject(url, String.class);
        if (response.contains("errcode")) {
            return null;
        }
        WeiXinUserInfo profile = null;
        try {
            profile = new ObjectMapper().readValue(response, WeiXinUserInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("获取到的微信信息 = " + profile);
        return profile;
    }

    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        // 查看源代码第一个添加的就是StringHttpMessageConverter，默认是处理ISO-8859-1字符集的，我们进行移除，定义我们需要的字符集格式转化
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return messageConverters;
    }
}
